package org.red_cross_service.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.red_cross_service.common.response.Response;
import org.red_cross_service.domain.dto.UserProcess;
import org.red_cross_service.domain.dto.Video;
import org.red_cross_service.domain.entity.ActivityEntity;
import org.red_cross_service.domain.entity.LearnRecordEntity;
import org.red_cross_service.mapper.ActivityMapper;
import org.red_cross_service.mapper.LearnRecordMapper;
import org.red_cross_service.utils.QueryWrapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class LearnRecordService {
    @Autowired
    LearnRecordMapper learnRecordMapper;
    @Autowired
    ActivityMapper activityMapper;

    @Transactional(rollbackFor = Exception.class)
    public Response updateUserVideoProcess(UserProcess process) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        ActivityEntity activity = activityMapper.selectOne(new QueryWrapper<ActivityEntity>().eq("activity_id", process.getActivityId()));
        //获取视频信息
        Video[] videos = mapper.readValue(activity.getVideosInfo(), Video[].class);
        LearnRecordEntity record = learnRecordMapper.selectOne(
                new QueryWrapper<LearnRecordEntity>()
                        .eq("activity_id", process.getActivityId())
                        .eq("user_id", process.getUserId())
        );
        if (record == null) {
            record = new LearnRecordEntity();
            //将Integer类型转换为Long
            record.setActivityId(process.getActivityId().longValue());
            record.setUserId(process.getUserId().longValue());
            record.setVideosStatus(0);
            record.setVideosProcess(mapper.writeValueAsString(new int[videos.length]));
            learnRecordMapper.insert(record);
        }
        //判断是否看完了当前视频
        if (process.getProcess() >= videos[process.getCurrentIndex()].getLength()) {
            //TODO：修改记录表中的videos_status
            Integer videosStatus = record.getVideosStatus();
            videosStatus|=1<<process.getCurrentIndex();
            record.setVideosStatus(videosStatus);
        }

        //获取当前活动下所有视频进度
        int[] videoProcess = mapper.readValue(record.getVideosProcess(), int[].class);
        //修改当前视频进度
        videoProcess[process.getCurrentIndex()] = process.getProcess();
        record.setVideosProcess(mapper.writeValueAsString(videoProcess));

        //更新
        learnRecordMapper.update(record, new QueryWrapper<LearnRecordEntity>()
                .eq("activity_id", process.getActivityId())
                .eq("user_id", process.getUserId())
        );
        return Response.success(record);
    }

    public Response update(LearnRecordEntity learnRecord) {
        return Response.success(learnRecordMapper.updateById(learnRecord));
    }

    public Response getLearnRecordList(LearnRecordEntity learnRecord) {
        return Response.success(
                learnRecordMapper.selectList(
                        QueryWrapperUtils.buildQuery(
                                learnRecord
                        )
                )
        );
    }

    public Response queryLearnRecordByUserId(Integer userId, Boolean type) {
        String sql = type ? "AND a.activity_end_time >= NOW()" : "AND a.activity_end_time <= NOW()";
        return Response.success(learnRecordMapper.queryLearnRecord(sql, userId));
    }

    public LearnRecordEntity selectOne(LearnRecordEntity learnRecord) {
        return learnRecordMapper.selectOne(QueryWrapperUtils.buildQuery(learnRecord));
    }
}
